<template>
  <!-- <VPage class="app-container"> -->
  <el-scrollbar style="width: 100%;" class="px-2 py-2" height="100vh - 120px">
    <el-card class="mb-2">
      <div class="flex justify-between mb-4">
        <div class="flex">
          <template v-if="!type">
            <el-select class="selectClass" v-model="skuType" style="max-width: 150px">
              <el-option v-for="item in skuOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
            <el-input v-model="sku" placeholder="请输入SKU" @change="changeSKU" />
          </template>
        </div>
        <div v-if="detail"><el-button type="primary" @click="quality">质检完成</el-button></div>
      </div>
      <el-row class="py-2 px-2" style="background-color: #EAF3FF;border-radius: 8px;" v-if="detail">
        <el-col :span="6">
          <div class="item">SKU：<span>{{ detail.sku }} </span></div>
        </el-col>
        <el-col :span="6">
          <div class="item">颜色：<span>{{ detail.color }} </span></div>
        </el-col>
        <!-- <el-col :span="6">
          <div class="item">尺寸：<span>{{detail.sku}} </span></div>
        </el-col> -->
        <el-col :span="6">
          <div class="item">物流属性：<span>{{ detail.logistics_attributes_name }} </span></div>
        </el-col>
        <el-col :span="6">
          <div class="item">
            产品尺寸：<span>长:{{ detail.product_size_cm?.length }} 宽:{{ detail.product_size_cm?.width }} 高:{{
              detail.product_size_cm?.height }}
            </span></div>
        </el-col>
        <el-col :span="6">
          <div class="item">
            包装尺寸：<span>长:{{ detail.packing_size_cm?.length }} 宽:{{ detail.packing_size_cm?.width }} 高:{{
              detail.packing_size_cm?.height }}
            </span></div>
        </el-col>
        <el-col :span="6">
          <div class="item">
            尺寸：<span></span></div>
        </el-col>
        <el-col :span="6">
          <div class="item">产品毛重：<span>{{ detail.gross_weight_g }}/G </span></div>
        </el-col>
        <el-col :span="6">
          <div class="item">产品净重：<span>{{ detail.net_weight_g }}/G </span></div>
        </el-col>

        <el-col :span="6">
          <div class="item">采购员：<span>{{ detail.purchaser_text }} </span></div>
        </el-col>
        <el-col :span="6">
          <div class="item">开发员：<span>{{ detail.developer_text }} </span></div>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="mb-2" v-if="detail">
      <div id="spuInfo" class="header-title mb-4 w-28">基础信息</div>
      <el-row :gutter="16" style="font-size: 16px;">
        <el-col :span="15">
          <el-row :gutter="16" class="flex items-center">
            <el-col :span="6">
              <div class="base-item">采购单号：<span>{{ detail.receipt_number }}</span></div>
            </el-col>
            <el-col :span="6">
              <div class="base-item">平台下单号：<span>{{ detail.platform_order_no }}</span></div>
            </el-col>
            <el-col :span="6">
              <div class="base-item">申请质检数量：<span>{{ detail.num }}</span></div>
            </el-col>
            <el-col :span="6">
              <div class="base-item">图片：<el-button type="primary" @click="handlePhotograph">拍照</el-button> 共{{
                abnormalPicture?.length || '0' }}张 <span class="base-text-color cursor-pointer"
                  @click="handleViewImage">查看</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="">质检数量</div>
              <VGroup>
                <el-select class="selectClass" v-model="detail.qc_type" placeholder="质检状态" clearable
                  @change="changeQcType">
                  <el-option v-for="item in options['stockin.qcOrder']?.[0].qcType" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
                <el-input v-model="detail.qc_num" placeholder="质检数量" :disabled="detail.qc_type == 0"
                  @input="inputQcNum"></el-input>
              </VGroup>
            </el-col>
            <el-col :span="6">
              <div class="">良品数量</div>
              <el-input v-model="detail.good_num" placeholder="良品数量" @input="inputNum"></el-input>
            </el-col>
            <el-col :span="8">
              <div class="">不良品数量</div>
              <VGroup>
                <el-select class="selectClass" v-model="detail.bad_type" placeholder="不良类型" clearable>
                  <el-option v-for="item in options['stockin.qcOrder']?.[0].badType" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
                <el-input v-model="detail.bad_num" placeholder="不良品数量" @input="inputNum"></el-input>
              </VGroup>
            </el-col>
            <el-col :span="4" v-if="type">
              <div class="">接收状态</div>
              <VGroup>
                <el-select class="selectClass" v-model="detail.accept_status" placeholder="不良类型" clearable>
                  <el-option v-for="item in acceptOption" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </VGroup>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="9">
          <div class="w-full">
            <div>质检备注</div>
            <div>
              <el-input v-model="detail.remark" :autosize="{ minRows: 4, maxRows: 4 }" type="textarea"
                placeholder="请输入"></el-input>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="mb-2" v-if="detail">
      <div id="spuInfo" class="header-title mb-4 w-28">产品中文名称</div>
      <div class="text-xl font-medium">{{ detail.sku_cn_title }}</div>
    </el-card>
    <el-row :gutter="10" class="mb-2" v-if="detail">
      <el-col :span="12">
        <el-card>
          <div id="spuInfo" class="header-title mb-4 w-28">质检备注</div>
          <div class="quality-remark">{{ detail.inspection_remark || '暂无备注' }}</div>
        </el-card>

      </el-col>
      <el-col :span="12">
        <el-card>
          <div id="spuInfo" class="header-title mb-4 w-28">重点检测事项</div>
          <div class="quality-remark">
            <template v-if="detail.point_check_items.length">
            <div class="flex mb-4" v-for="(item,index) in detail.point_check_items" :key="index">
              <el-input style="width: 140px; margin-right: 8px;" :value="item.item_name"></el-input>
              <el-input :value="item.item_content"></el-input>
            </div>
          </template>
          <div class="text-[#999999]">暂无检测事项</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-card class="mb-2" v-if="detail">
      <div class="flex flex-wrap">
        <div class="image-class" v-for="item in detail.image" :key="item">
          <img :src="item">
        </div>
      </div>
    </el-card>
  </el-scrollbar>
  <!-- </VPage> -->



  <el-dialog v-model="visible" title="单据选择" width="720" show-footer show-zoom resize @close="close">
    <template #default>
      <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" highlight-current-row :header-cell-style="{
        background: '#F6FAFF'
      }" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="单号" prop="qc_order_no" width="200"></el-table-column>
        <el-table-column label="采购单号" prop="receipt_number" width="200" />
        <el-table-column label="SKU" prop="sku" width="120" />
        <el-table-column label="数量" prop="num" />
      </el-table>
    </template>

    <template #footer>
      <div class="flex justify-center py-2">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save()">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <DialogImage ref="DialogImageRef"></DialogImage>
  <DialogPhotograph ref="DialogPhotographRef" @success="successImage"></DialogPhotograph>
</template>
<script setup>
import { getEnums } from '@/api/public'
import { qcOrderDetail, factoryOrderDetail, readyQcOrder, completeQc, factoryCompleteQc } from './api/index'
import { onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import action from '@/utils/action.js'
import DialogImage from '@/components/DialogImage/index.vue'
import DialogPhotograph from '@/components/DialogPhotograph/index.vue'
import { useRouter, useRoute } from 'vue-router';

const route = useRoute()
const router = useRouter()

const skuOption = [
  {
    label: 'SKU',
    value: 'sku'
  }
]

const acceptOption = [
  {
    label: '允收',
    value: 1
  },
  {
    label: '不允收',
    value: 0
  }
]

const data = reactive({
  options: [],
  skuType: 'sku',
  type: '',
  sku: '',
  detail_id: '',
  detail: '',
  visible: false,
  tableData: [],
  multipleSelection: [],
  abnormalPicture: []
})
const { options, skuType, sku, type, detail_id, detail, visible, tableData, multipleSelection, abnormalPicture } = toRefs(data)

// 获取枚举类
const fetchOption = async () => {
  getEnums({
    version: "v1", "name": [
      "stockin.qcOrder"
    ]
  }).then(res => {
    options.value = res.data
  })
}
fetchOption()

const getDetail = async () => {
  try {
    const request = type.value == 'qc-factory' ? factoryOrderDetail : qcOrderDetail
    const res = await request({
      detail_id: detail_id.value
    })
    detail.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

const changeSKU = async (val) => {
  if (!val) {
    return
  }
  try {
    const res = await readyQcOrder({
      sku: val,
      batch_code: val
    })
    if (res.data.length == 1) {
      detail_id.value = res.data[0].detail_id
      getDetail()
    } else {
      tableData.value = res.data
      visible.value = true
    }
  } catch (e) {
    throw Error(e)
  }
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// sku存在多条选择回调
const save = async (val) => {
  console.log(multipleSelection.value)
  if (multipleSelection.value.length == 0) {
    ElMessage.error('至少选择一项')
    return
  } else if (multipleSelection.value.length > 1) {
    ElMessage.error('最多选择一项')
    return
  } else {
    visible.value = false
    detail_id.value = multipleSelection.value[0].detail_id
    getDetail()
  }
}

// 质检完成
const quality = async () => {
  if (detail.value.qc_type == 0 && detail.value.num != detail.value.qc_num) {
    ElMessage.error('全检状态,质检数量必须等于申请数量')
    return
  }
  try {
    const form = {
      detail_id: detail_id.value,//质检明细id
      qc_num: detail.value.qc_num,//质检数
      good_num: detail.value.good_num,//良品数
      bad_num: detail.value.bad_num,//不良品数
      bad_type: detail.value.bad_type,//不良类型
      qc_type: detail.value.qc_type,//质检类型
      accept_status: detail.value.accept_status, //是否允收 
      remark: detail.value.remark//质检备注
    }

    const request = type.value == 'qc-factory' ? factoryCompleteQc : completeQc
    const res = await request(form)
    ElMessage.success(res.message)
    if (type.value == 'qc-factory') {
      action.setGlobalState({
        changeMicoTabsPath: {
          type: 'closeActiveTab',
        }
      })
    } else {

    }
  } catch (e) {
    throw Error(e)
  }
}

const DialogPhotographRef = ref()
const handlePhotograph = () => {
  DialogPhotographRef.value.open(type.value == 'qc-factory' ? 4 : 3, detail_id.value)
}

const DialogImageRef = ref()
const handleViewImage = () => {
  DialogImageRef.value.open(type.value == 'qc-factory' ? 4 : 3, detail_id.value)
}

const successImage = (url) => {
  abnormalPicture.value.push({
    url
  })
}

const changeQcType = (val) => {
  if (val == 0) {
    detail.value.qc_num = detail.value.num
  }


}

const inputQcNum = (val) => {
  detail.value.good_num = ''
  detail.value.bad_num = ''
}

const inputNum = (val) => {
  const qc_num = Number(detail.value.good_num) + Number(detail.value.bad_num)
  if (detail.value.qc_type == 1) {
    detail.value.qc_num = qc_num
  } else {
    if (qc_num != detail.value.num) {
      ElMessage.error('质检数量必须等于申请质检数量,请修改')
    }
  }
}



onMounted(() => {
  if (route?.query.detail_id) {
    type.value = route.query?.type
    detail_id.value = route?.query?.detail_id
    getDetail()
  }
})

</script>
<style lang="scss" scoped>
.header-title {
  font-weight: bold;
  padding-left: 6px;
  position: relative;
}

.header-title::before {
  content: '';
  display: block;
  position: absolute;
  left: 0;
  top: 5px;
  width: 2px;
  height: 14px;
  background: #3366F1;
}

.item {
  padding: 8px 0;
  color: #999999;

  span {
    color: #333333;
  }
}

.base-item {
  padding: 8px 0;
  color: #999999;
  font-size: 14px;

  span {
    color: #333333;
  }
}

.image-class {
  width: 320px;
  // height: 240px;
  margin-right: 33px;
  margin-bottom: 24px;
}

.quality-remark {
  min-height: 325px;
}
</style>